#coding:utf8
import urllib2
from datetime import datetime, timedelta
import time
from google.appengine.ext import db
from google.appengine.ext.db import djangoforms
from google.appengine.api import mail
from django import http, shortcuts
#from django.conf import settings
#settings._target = None

BUY_IN = 'buy_in'
SELL_OUT = 'sell_out'
SAFE = 'safe'

class GoldConfig(db.Expando):
    my_spy_on = db.BooleanProperty(default = False)
    my_buy_in = db.FloatProperty()   # 低于此价，可买入，一小时内邮件通知一次
    my_sell_out = db.FloatProperty() # 高于此价，可卖出，一小时内邮件通知一次
    my_email = db.StringProperty(default = 'toontong@163.com')
    last_result = db.StringProperty(choices = [BUY_IN, SELL_OUT, SAFE], default = SAFE) # safe 代表价格在buy_in与sell_out中间
    last_send_time = db.FloatProperty()
    send_mail_after_second = db.IntegerProperty(default = 60 * 60)

class ConfigForm(djangoforms.ModelForm):
    class Meta:
        model = GoldConfig
        exclude = []

_config = GoldConfig.get_by_key_name('default')
if not _config:
    _config = GoldConfig(key_name = 'default')
    _config.last_send_time = time.time()
    _config.my_buy_in, _config.my_sell_out = 0.0, 0.0
    _config.put()

def index(request):
    global _config
    form = ConfigForm(data = request.POST or None, instance = _config)
    if request.POST:
        _config = form.save(commit = False)
        _config.last_send_time = time.time()
        _config.put()
    return shortcuts.render_to_response('gold.html', {'form': form})

lastCall = None
def minutes(request):
    '''工行黄金的交易时间一般为周一早7:00到周六早4:00，'''
    now = datetime.utcnow() + timedelta(hours =+ 8)
    weekday = now.isoweekday()
    if weekday == 7:
         return http.HttpResponse('now is Sunday %s , rest day.' % now)
    if weekday == 6 and now.hour > 4:
         return http.HttpResponse('now is Saturday %s , rest day.' % now)
    
    global _config, lastCall
    if _config.my_spy_on is False:
        return http.HttpResponse('the spy do not open!')
    if lastCall is None or lastCall == 'cngold.success' or lastCall == 'icbc.error':
        try:
            yhmrj, yhmcj = cngold_org()
            lastCall = 'cngold.success'
        except Exception , e:
            lastCall ='cngold.error'
            raise e
    elif lastCall is None or lastCall == 'icbc.success' or lastCall == 'cngold.error':
        try:
            yhmrj, yhmcj = icbc_get()
            lastCall = 'icbc.success'
        except Exception , e:
            lastCall = 'icbc.error'
            raise e
    else:
        lastCall = None

    send = False
    if yhmcj < _config.my_buy_in:
        _config.last_result = BUY_IN
        send = _send_mail(_config.my_email, 'Buy in', 'You can buy in now ! the price is %s RMB' % yhmcj)
    elif yhmrj > _config.my_sell_out:
        _config.last_result = SELL_OUT
        send = _send_mail(_config.my_email, 'Sell out', 'You can sell out now !, the price is %s RMB' % yhmrj)
    else:
        _config.last_result = SAFE

    return http.HttpResponse('now is %s <br />status: %s , send: %s <br />the bank buy in:%s ; sell out: %s <br />you buy in price is: %s, you want to sell out on %s.'
                             % (now, _config.last_result, send, yhmrj, yhmcj, _config.my_buy_in, _config.my_sell_out))

def _send_mail(email, subject, txt):
    now = time.time()
    if _config.send_mail_after_second and (now - _config.last_send_time) < _config.send_mail_after_second:
        return False
    mail.send_mail(sender = "chuantong.huang@gmail.com",
                   to = email,
                   subject = "%s - Gold Spy notice!" % subject,
                   body = txt)
    _config.last_send_time = now
    _config.put()
    return datetime.now()

URL = 'http://www.icbc.com.cn/FinanceMarket/gold/Default.aspx'
def icbc_get(url = URL):
    from sgmllib import SGMLParser
    txt = urllib2.urlopen(url).read()
    class myParser(SGMLParser):
        is_span = 0
        _mrj, _mcj = 0, 0

        def start_span(self, attrs):
            for k, v in attrs:
                if k =='id':
                  if v == 'ctl00_Content_Boby_AccountGold1_Label_mrj1':
                    self.is_span = 1
                  elif v == 'ctl00_Content_Boby_AccountGold1_Label_mcj1':
                    self.is_span = 2

        def end_span(self):
            self.is_span = 0

        def handle_data(self, text):
            if self.is_span == 1:
                self._mrj = float(text[:6])
            elif self.is_span == 2:
                self._mcj = float(text[:6])

        def printResult(self, content = True):
            print self._mrj, self._mcj

    lp = myParser()
    lp.feed(txt)
    return lp._mrj, lp._mcj

def cngold_org():
    url = 'http://tool.cngold.org/plus/qjson.do?codes=CNYAAU&names=%E5%B7%A5%E8%A1%8C%E7%BA%B8%E9%BB%84%E9%87%91%E4%BA%BA%E6%B0%91%E5%B8%81%E6%8A%A5%E4%BB%B7'

    txt = urllib2.urlopen(url).read()

    d = eval(txt)[0]['message']
    return d['buy'], d['sell']
    
    
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.out.write('Hello, webapp World!')

application = webapp.WSGIApplication(
                                     [('/', MainPage)],
                                     debug=True)

def main():
  run_wsgi_app(application)

  
  
if __name__ == "__main__":
  main()
if __name__ == '__main__':
    print _get(URL)

